import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:identification_photo/base/base_view_model.dart';
import 'package:identification_photo/config/constants.dart';
import 'package:identification_photo/repository/baidu_ai_repository.dart';
import 'package:identification_photo/utils/color_util.dart';
import 'package:identification_photo/utils/file_util.dart';
import 'package:identification_photo/utils/image_util.dart';
import 'package:identification_photo/utils/permission_util.dart';
import 'package:identification_photo/utils/toast_util.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

class HomeViewModel extends BaseViewModel {
  //实例化选择图片
  final ImagePicker picker = ImagePicker();

  ///获取到得base64
  String? base64Str;

  /// 合成以后的图片数据
  Uint8List? finalImgBuffer;
  String tipInfo = '''拍照建议：
1.表情自然，面部无遮挡，抬头挺胸
2.找人他协助，用后置摄像头拍摄
3.穿深色衣服，使用白色背景拍摄效果更佳''';

  ///可选则的颜色列表
  List<Color> colorList = [
    const Color(0xffffffff),
    const Color(0xff428eda),
    const Color(0xfffe0000)
  ];

  /// 背景颜色 默认是白色
  Color selectColor = Colors.white;

  List<Map<String, dynamic>> photoPixel = [
    {"ratioX": 295.0, "ratioY": 413.0, "name": "oneInch"},
    {"ratioX": 260.0, "ratioY": 390.0, "name": "idCardHead"},
    {"ratioX": 413.0, "ratioY": 626.0, "name": "twoInch"},
    {"ratioX": 390.0, "ratioY": 567.0, "name": "smallTwoInch"},
  ];
  int pixelSelect = 0;
  File? finalImage;

  onLoad() async {
    ///这里可以做一些初始化的操作
    setIdle();
  }

//用户本地图片
  File? _userImage; //存放获取到的本地路径
  Future getPicPath(ImageFrom score) async {
    //选择相册
    try {
      final pickerImages = await ImageUtil.pickSinglePic(score);
      if (pickerImages != null) {
        _userImage = File(pickerImages.path);
        debugPrint('你选择的本地路径是：${_userImage.toString()}');
      } else {
        ToastUtil().showBottomToast("用户取消选图片");
      }
      if (_userImage != null) {
        final croppedFile = await ImageUtil.cropImage(
            image: _userImage,
            width: photoPixel[pixelSelect]["ratioX"],
            height: photoPixel[pixelSelect]["ratioY"]);
        debugPrint('你选择的本地路径是：${croppedFile?.path.toString()}');
        if (croppedFile != null) {
          finalImage = File(croppedFile.path);
          if (finalImage == null) {
            ToastUtil().showBottomToast("文件出错了,请重试");
            return;
          }
          String base64 = await FileUtil.file2Base64(finalImage!);

          ///这里为了方便请求接口的时候请求token 正常他是有半小时的过期时间 这里你应该做一下处理
          String token = await BaiduAiRepository.getToken();
          Map<String, dynamic> param = {"image": base64, "access_token": token};
          base64Str = await BaiduAiRepository.getBase64(param);
          await buildPic();
        }
      }
    } catch (e, stackTrace) {
      setError(e, stackTrace);
    }
  }

  selectPixel(value) {
    pixelSelect = value;
    notifyListeners();
  }

  clean() {
    finalImgBuffer = null;
    notifyListeners();
  }

  buildPic({color = Colors.white}) async {
    if (base64Str == null) {
      ToastUtil().showCenterToast("请制作完图片再换色");
      return;
    }
    selectColor = color;
    ByteData imgBytes = await ImageUtil.generateImageData(
        width: photoPixel[pixelSelect]["ratioX"],
        height: photoPixel[pixelSelect]["ratioY"],
        bgColor: color,
        imageFile: base64Str);
    finalImgBuffer = FileUtil.byteData2Uint8List(imgBytes);

    notifyListeners();
  }

  savePic() async {
    if (finalImgBuffer == null) {
      ToastUtil().showCenterToast("请制作完图片再保存");
      return;
    }
    PermissionUtil.checkPermission(
        permissionList: [Permission.photos, Permission.storage],
        onFailed: () => {ToastUtil().showCenterToast("图片处理错误")},
        onSuccess: () async {
          final result = await FileUtil.saveImage2Album(finalImgBuffer!,
              quality: 100, name: "photo");
          if (result != null) {
            ToastUtil().showCenterToast("保存成功~~~");
          } else {
            ToastUtil().showCenterToast("保存失败~~~");
          }
        });
  }
}
